package dk.aiszone.lang.sql;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import dk.aiszone.lang.sql.interfaces.SQLConstraint;
import dk.aiszone.lang.sql.interfaces.SQLJoin;

/**
 * Representation of the inner join operation.
 * 
 * @author Ais
 */
public class SQLInnerJoin extends AbstractSQLObject implements SQLJoin {

    private SQLAnd basisAnd;
    private SQLAnd currentAndStatement;

    private final List<SQLJoin> joins = new ArrayList<SQLJoin>();
    private final SQLTable table;

    /**
     * Constructor for the <code>SQLInnerJoin</code> class.
     * 
     * @param table
     *            <code>SQLTable</code> to join.
     */
    public SQLInnerJoin(SQLTable table) {
        this.table = table;
    }

    @Override
    public void addConstraint(SQLConstraint constraint) {
        if (currentAndStatement == null) {
            currentAndStatement = new SQLAnd(constraint);
            basisAnd = currentAndStatement;
        } else {
            SQLAnd tmp = new SQLAnd(constraint);
            currentAndStatement.setConstraint2(tmp);
            currentAndStatement = tmp;
        }
    }

    @Override
    public void addConstraint(SQLOr or) {
        if (currentAndStatement == null) {
            currentAndStatement = new SQLAnd(or);
            basisAnd = currentAndStatement;
        } else {
            SQLAnd tmp = new SQLAnd(or);
            currentAndStatement.setConstraint2(tmp);
            currentAndStatement = tmp;
        }
    }

    @Override
    public void addField(SQLField field) {
        table.addField(field);
    }

    @Override
    public void addJoin(SQLJoin join) {
        joins.add(join);
    }

    @Override
    public SQLTable getJoinedTable() {
        return table;
    }

    @Override
    public SQLResult prepareSQL(SQLResult sql) {
        sql.append(" INNER JOIN ");
        table.prepareSQL(sql);
        sql.append(" ON (");
        basisAnd.prepareSQL(sql);
        sql.append(")");
        for (Iterator<SQLJoin> iterator = joins.iterator(); iterator.hasNext();) {
            iterator.next().prepareSQL(sql);
        }

        return sql;
    }
}